package com.example.base.component;

import com.example.base.dto.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Slf4j
//@ControllerAdvice
public class ProjectExceptionHandler {

    private ObjectMapper objectMapper;

    @Autowired
    public ProjectExceptionHandler(ObjectMapper objectMapper){
        this.objectMapper = objectMapper;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R<ObjectNode> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors =  result.getAllErrors();
        List<String> errorList = Lists.newArrayList();
        for (ObjectError error : errors){
            //默认信息
            errorList.add(error.getDefaultMessage());
        }
        return R.paramError(null, StringUtils.join(errorList));
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R<String> exceptionHandler(Exception e){
        log.error("系统处理异常", e);
        return R.error("系统处理异常", e.getMessage());
    }
}
